
package com.campus.market;
import com.campus.common.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.Map;
@RestController @RequestMapping("/api/items")
public class ItemController {
  @Autowired private ItemRepository repo;
  @PostMapping
  public ResponseEntity<?> create(@Valid @RequestBody CreateItemReq req){
    Item i = new Item();
    i.setUserId(req.userId());
    i.setTitle(req.title()); i.setCategory(req.category());
    i.setDescription(req.description()); i.setPrice(req.price());
    repo.save(i);
    return ResponseEntity.ok(ApiResponse.ok(Map.of("id", i.getId())));
  }
  @GetMapping
  public ResponseEntity<?> list(@RequestParam(defaultValue="") String category,
                                @RequestParam(defaultValue="") String keyword,
                                @RequestParam(defaultValue="0") int page,
                                @RequestParam(defaultValue="10") int size){
    Pageable p = PageRequest.of(page, size);
    return ResponseEntity.ok(ApiResponse.ok(
      repo.findByCategoryContainingAndTitleContainingAllIgnoreCase(category, keyword, p)));
  }
  public record CreateItemReq(@Min(1) Long userId, @NotBlank String title, String category, String description,
                              @Min(0) BigDecimal price) {}
}
